<template>
	<div class="userbox">
		<div class="cont">
			<div class="cont-header">
				<h2>{{ $t('short_data.subtitle.title') }}</h2>
			</div>
			<div class="subtitlebox">
				<div class="videobox">
					<!-- crossorigin="anonymous" -->
          <video controls class="videoItem" @durationchange="durationchange" ref="video" id="video" @pause="palyPause" @canplay="canplay" @timeupdate="onTimeupdate">
            <track
              v-for="(item,index) in cationArr"
              :key="index"
              :label="item.label"
              kind="subtitles"
              :srclang="item.lang"
              :src="item.src"
              :default="item.default"
            />
          </video>
					<el-button type="warning" icon="el-icon-circle-plus" class="addBtn" v-if="subtitleList.length&&type!=4" @click="handlePop(3,true)">{{ $t('short_data.subtitle.add') }}</el-button>
					<el-button class="addBtn gptbtn" v-if="$route.query.gpt==1" @click="initiateGPT">{{ $t('short_data.sub_transBtn') }}</el-button>
				</div>
				<!-- <input multiple ref="fileRef" type="file" @change="inputFile"> -->
				<div class="oprationbox" v-if="!subtitleList.length && showUploadBox">
					<p class="title">{{ setShortName(videoData.title) }}</p>
					<span class="tips" v-if="!isWait">{{ $t('short_data.subtitle.uploadTips') }}</span>
					<span class="wait tips" v-if="isWait">{{ $t('short_data.subtitle.waitTips') }}</span>
					<div class="btns" v-if="!isWait">
						<div class="localbtn" @click="type=1;dialogVisible=true;">
							<img class="icon" src="shortsImg/local_icon.png">
							<span>{{ $t('short_data.subtitle.localBtn') }}</span>
						</div>
						<div class="localbtn" @click="type=2;dialogVisible=true">
							<img class="icon" src="shortsImg/ai_icon.png">
							<span>{{ $t('short_data.subtitle.tcTitle') }}</span>
						</div>
					</div>
				</div>
				<div class="oprationbox" v-else-if="type!=4">
					<p class="title">{{ setShortName(videoData.title) }}</p>
					<span class="wait tips" v-if="isWait">{{ $t('short_data.subtitle.waitTips') }}</span>
					<!-- <el-button @click="downloadImg">截图</el-button> -->
					<!-- <img v-for="item in imglist" :src="item"> -->
					<scTable ref="table" :data="subtitleList" row-key="id" stripe border :header-cell-style="{background: '#FFF3D7',color: '#666'}" :hidePagination="true" :isDIY="true" :hideSetting="true" :hideRefresh="true">
						<el-table-column :label="$t('short_data.subtitle.language')" width="auto" >
							<template #default="scope">
								{{ setLang(scope.row.srtLang) }}
							</template>
						</el-table-column>
						<el-table-column :label="$t('short_data.subtitle.time')" width="auto" prop="createAt">
						</el-table-column>
						<el-table-column :label="$t('short_data.subtitle.operate')" width="auto" align="center">
							<template #default="scope">
								<el-button-group class="operationbox">
									<el-button icon="el-icon-tickets" @click="detail(scope.row)">{{ $t('short_data.subtitle.detail') }}</el-button>
									<el-button type="danger" icon="el-icon-delete" @click="deleteSub(scope.row)">{{ $t('short_data.subtitle.delete') }}</el-button>
								</el-button-group>
							</template>
						</el-table-column>
					</scTable>
				</div>
				<div class="rightbox" v-if="type==4">
					<div class="formData">
						<div class="item" v-for="(item,index) in srtList" :key="index" @click="viewZM(item,index)" :class="{isItem: current==index}">
							<div class="item-index" v-if="item.stime">
								<span class="xh">#{{ index+1 }}</span>
								<el-icon class="del_icon" @click="delsubTitleMethods(index)"><component :is="oicon('el-icon-delete')" /></el-icon>
								<el-icon class="add_icon" @click="addsubTitleMethods(item,index)"><component :is="oicon('el-icon-circle-plus')" /></el-icon>
							</div>
							<div class="item-time" v-if="item.stime">
								<div class="timef">
									<el-input class="timeInput" v-model="item.stime"></el-input>
									<el-input class="timeInput" v-model="item.etime"></el-input>
								</div>
							</div>
							<div class="item-label">
								<el-input class="textInput" v-model="item.text" type="textarea" :rows="4" resize="none"></el-input>
							</div>
						</div>
						<div v-if="$route.query.gpt==1 && gptForm.srtText && !gptForm.isTransEnd">
							<el-button @click="countinueAsk" :loading="gptForm.isLoading">{{ $t('short_data.sub_countinueAsk') }}</el-button>
						</div>
					</div>
				</div>

			</div>
			<!-- time slider -->
			<div class="sliderBox" v-if="type==4">
				<div class="scrollbox">
					<div class="timeOperabox">
						<div class="leftside" >
							<el-input v-model="timelineData.nowTime" disabled="true" class="leftside-time"></el-input>
							<el-button type="text" icon="el-icon-back" v-copy="timelineData.nowTime">Copy</el-button>
						</div>
						<div class="rightside">
							<el-icon class="out_icon"><component :is="oicon('el-icon-zoom-out')" /></el-icon>
							<el-slider
								class="slider"
								v-model="scale"
								:max="2"
								:min="0"
								@input="scaleChange"
								:step="1">
							</el-slider>
							<el-icon class="in_icon"><component :is="oicon('el-icon-zoom-in')" /></el-icon>
						</div>
					</div>
					<!-- <TimeLineCanvas
						:height="timelineData.height"
						:timeRange="timelineData.timeRange"
						:startMeddleTime="timelineData.startMeddleTime"
						:markTime="timelineData.markTime"
						ref="timeLineCanvas"
						@click="clickCanvas"
						@getHour="getHour"
					></TimeLineCanvas> -->
					<timeline v-if="timelineData.duration>0" ref="Timeline" :initZoomIndex="scale" :centerLineStyle="{color: '#BB9B51'}" :showHoverTime="false" backgroundColor="#fff" lineColor="#ccc" textColor="#000" :showDateAtZero="false" :formatTime="formatTime" :duration="timelineData.duration" :initTime="timelineData.initTime" :timeRange="timelineData.timeRange" :timeSegments="timelineData.markTime" class="timeline" @setZoom="setZoom" @click_timeline="click_timeline" @dragTimeChange="dragTimeChange"></timeline>
				</div>
			</div>
			<div id="footer" v-if="type==4">
				<el-button @click="type=3" :loading="gptForm.isLoading">{{$t('table_data.cancelText')}}</el-button>
				<el-button @click="saveSrt" type="primary" :loading="gptForm.isLoading">{{$t('table_data.saveText')}}</el-button>
			</div>

		</div>
		<!-- 弹窗框 -->
		<sCDialog :modelValue="dialogVisible" :showFullscreen="false" :showClose="false" width="30%" :close-on-click-modal="false">
      <template v-slot:header>
        <span class="scdialog-title">{{ type==2?$t('short_data.subtitle.tcTitle'):type==1?$t('short_data.subtitle.localBtn'):$t('short_data.subtitle.add') }}</span>
      </template>
      <div class="cont">
				<p v-if="type!=3">{{ type==2?$t('short_data.subtitle.selectTips'):$t('short_data.subtitle.selectFileTips') }}</p>
				<el-checkbox-group v-model="langList" v-if="type==2">
					<el-checkbox label="en-US">{{ $t('short_data.subtitle.english') }}</el-checkbox>
					<el-checkbox label="ja-JP">{{ $t('short_data.subtitle.japanese') }}</el-checkbox>
					<el-checkbox label="zh-CN">{{ $t('short_data.subtitle.simplified') }}</el-checkbox>
					<el-checkbox label="zh-TW">{{ $t('short_data.subtitle.traditional') }}</el-checkbox>
					<el-checkbox label="fr-FR">{{ $t('short_data.subtitle.french') }}</el-checkbox>
				</el-checkbox-group>
				<div class="el-checkbox-group" v-else-if="type==1">
					<input multiple v-show="false" ref="srtFile" type="file" @change="inputSrtFile">
					<el-radio v-model="srtLang" label="en-US">{{ $t('short_data.subtitle.english') }}</el-radio>
					<el-radio v-model="srtLang" label="ja-JP">{{ $t('short_data.subtitle.japanese') }}</el-radio>
					<el-radio v-model="srtLang" label="zh-CN">{{ $t('short_data.subtitle.simplified') }}</el-radio>
					<el-radio v-model="srtLang" label="zh-TW">{{ $t('short_data.subtitle.traditional') }}</el-radio>
					<el-radio v-model="srtLang" label="fr-FR">{{ $t('short_data.subtitle.french') }}</el-radio>
				</div>
				<div class="popbtns" v-else>
					<div class="localbtn" @click="type=1;dialogVisible=true;">
						<img class="icon" src="shortsImg/local_icon.png">
						<span>{{ $t('short_data.subtitle.localBtn') }}</span>
					</div>
					<div class="localbtn" @click="type=2;dialogVisible=true">
						<img class="icon" src="shortsImg/ai_icon.png">
						<span>{{ $t('short_data.subtitle.tcTitle') }}</span>
					</div>
				</div>
      </div>
      <template v-slot:footer>
        <div class="diaFooter">
          <el-button @click="dialogVisible=false" :loading="gptForm.isLoading">{{$t('table_data.cancelText')}}</el-button>
          <el-button type="primary" @click="submit()" v-if="type!=3">{{$t('short_data.step.confirm')}}</el-button>
        </div>
      </template>
    </sCDialog>
		<!-- gpt翻译 -->
		<sCDialog :modelValue="showGptDialog" :showFullscreen="false" :showClose="false" width="80%" :close-on-click-modal="false">
      <template v-slot:header>
				<div class="gptheadbox">
					<span class="scdialog-title">{{ type==2?$t('short_data.subtitle.tcTitle'):type==1?$t('short_data.subtitle.localBtn'):$t('short_data.subtitle.add') }}</span>
					<el-button @click="contrastSrt">{{ gptForm.showContrast?'隐藏':'显示' }}完整转换结果</el-button>
				</div>
      </template>
			<div class="gptCont">
				<!-- 字幕对比 -->
				 <div class="allSrtbox" v-if="gptForm.showContrast">
						<div class="form-group">
								<p>转换前</p>
								<el-input v-model="gptForm.originalSrt" type="textarea" :rows="27" resize="none"/>
						</div>
						<div class="form-group">
								<p>转换后</p>
								<el-input v-model="gptForm.srtText" type="textarea" :rows="27" resize="none"/>
						</div>
				 </div>
				<div class="gptleftbox">
					<div class="form-group">
							<label for="srtFile">{{ $t('short_data.sub_file') }}</label>
							<input id="srtFile" multiple ref="srtFile" type="file" @change="inputSrtFileToString">
							<el-input v-model="gptForm.srt" type="textarea" :rows="27" />
					</div>
				</div>
				<div class="gptrightbox">
					<div class="form-group-nborder">
							<el-dropdown trigger="click">
								<div>{{ $t('short_data.sub_historyWord') }}<el-icon class="add_icon"><component :is="oicon('el-icon-arrow-down')" /></el-icon></div>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item v-for="(item,index) in gptForm.words" :key="index" @click="gptForm.promptWord=item">
											{{ item }}
										</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
							<!-- <div class="history">
								<span v-for="(item,index) in gptForm.words" :key="index" @click="gptForm.promptWord=item">{{ item }}</span>
							</div> -->
					</div>
					<div class="form-group">
							<label for="promptWord">{{ $t('short_data.sub_word') }}</label>
							<el-input v-model="gptForm.promptWord" type="textarea" :rows="6" />
					</div>
					<!-- <div class="form-group radio-group">
							<p>源语言：</p>
							<el-radio v-model="gptForm.oldsrtLang" label="en-US">{{ $t('short_data.subtitle.english') }}</el-radio>
							<el-radio v-model="gptForm.oldsrtLang" label="ja-JP">{{ $t('short_data.subtitle.japanese') }}</el-radio>
							<el-radio v-model="gptForm.oldsrtLang" label="zh-CN">{{ $t('short_data.subtitle.simplified') }}</el-radio>
							<el-radio v-model="gptForm.oldsrtLang" label="zh-TW">{{ $t('short_data.subtitle.traditional') }}</el-radio>
							<el-radio v-model="gptForm.oldsrtLang" label="fr-FR">{{ $t('short_data.subtitle.french') }}</el-radio>
					</div> -->
					<div class="form-group">
							<p>{{ $t('short_data.sub_selectLang') }}</p>
							<el-select v-model="gptForm.srtLang" placeholder="Select" @change="changeLang">
								<el-option
									v-for="item in gptForm.langList"
									:key="item.type"
									:label="item.label"
									:value="item.type"
								/>
							</el-select>
							<!-- <el-radio-group @change="changeLang" v-model="gptForm.srtLang">
								<el-radio label="en-US">{{ $t('short_data.subtitle.english') }}</el-radio>
								<el-radio label="ja-JP">{{ $t('short_data.subtitle.japanese') }}</el-radio>
								<el-radio label="zh-CN">{{ $t('short_data.subtitle.simplified') }}</el-radio>
								<el-radio label="zh-TW">{{ $t('short_data.subtitle.traditional') }}</el-radio>
								<el-radio label="fr-FR">{{ $t('short_data.subtitle.french') }}</el-radio>
							</el-radio-group> -->
					</div>
					<div class="form-group">
							<p>{{ $t('short_data.subtitle.transResult') }}</p>
							<el-input v-model="gptForm.transResultText" type="textarea" :rows="12" />
					</div>

				</div>
			</div>
      <template v-slot:footer>
        <div class="diaFooter">
          <el-button @click="gptForm.showContrast=false;showGptDialog=false" :loading="gptForm.isLoading">{{$t('table_data.cancelText')}}</el-button>
          <el-button v-if="!gptForm.isTransEnd" @click="countinueAsk" :loading="gptForm.isLoading">{{ $t('short_data.sub_countinueAsk') }}</el-button>
          <el-button type="primary" @click="restartAsk" :loading="gptForm.isLoading">{{ $t('short_data.sub_newStartAsk') }}</el-button>
        </div>
      </template>
    </sCDialog>
	</div>
</template>

<script>
import "vue3-video-play/dist/style.css";
import { videoPlay } from "vue3-video-play";
import Hls from 'hls.js';

import sCDialog from "@/components/scDialog"
import scShort from "@/components/scShorts"

// import timeline from "@/components/scSolider/index"
import timeline from "@/components/scSolider/tindex"
import dayjs from 'dayjs'


// 抽帧
// import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';
// const ffmpeg = createFFmpeg({
//   corePath: "js/ffmpeg-core.js",
//   log: true
// });



	export default {
		emits: ['success', 'closed'],
		components: {
			sCDialog,
			scShort,
			videoPlay,
			timeline
			// TimeLineCanvas,
			// VideoTimeline
		},
		mixins: [],
		data() {
			return {
				gptForm: {
				  promptWord: 'The following content is in English SRT subtitle format text. Please translate it into Japanese language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.',
					oldsrtLang: 'en-US',
					srtLang: 'ja-JP',
					srt: '',
					srtText: '',
					isLoading: false,
					words: [],
					langList: [
						{
							label: 'English',
							type: 'en-US'
						},
						{
							label: 'Japanese',
							type: 'ja-JP'
						},
						{
							label: 'French',
							type: 'fr-FR'
						},
						{
							label: '中文简体',
							type: 'zh-CN'
						},
						{
							label: '中文繁体',
							type: 'zh-TW'
						}
					],
					originalSrt: '',
					showContrast: false,
					isTransEnd: false,
					transResultText: ''
				},
				showGptDialog: false,
				m3u8Url: '',
				showUploadBox: true,
				srtLang: 'en-US',
				imglist: [],
				ssrc: '',
				isWait: false,
				scale: 0,
				current: -1,
				srtList: [],
				// timeRange: {start: '2024-05-11 00:00:00',end: '2024-05-11 00:03:58'},
				// 时间轴
				timelineData: {
					height: 150,
					startMeddleTime: "",
					nowTime: "00:00:00.000",
					initTime: 0,
					duration: 0,
					timeRange: {start: 0, end: 0},
					markTime: [
						// {
						// 	beginTime: 2,
						// 	endTime: 4,
						// 	color: "#c1a562",
						// 	textColor: "#fff",
						// 	text: "Being an actor and being a boxer,",
						// },
					]
				},
				apiObj: null,
				subtitleList: [],
				type: 0,
				langList: [],
				hls: null,
				dialogVisible: false,
				videoForm: {
					title: 'fffffffffffffffff',
					src: ''
				},
				// 字幕
				cationArr: [
					{
						label: 'English',
						lang: 'en',
						src: '',
						default: false,
						type: 'en-US'
					},
					{
						label: 'Japanese',
						lang: 'ja',
						src: '',
						default: true,
						type: 'ja-JP'
					},
					{
						label: 'French',
						lang: 'fr',
						src: '',
						default: false,
						type: 'fr-FR'
					},
					{
						label: '中文简体',
						lang: 'zh',
						src: '',
						default: false,
						type: 'zh-CN'
					},
					{
						label: '中文繁体',
						lang: 'zt',
						src: '',
						default: false,
						type: 'zh-TW'
					}
				],
        lang: {
          en: 'en_label',
          ja: 'ja_label',
          fr: 'fr_label',
          zh: 'zh_label',
          zt: 'zt_label',
        },
        responseArr: ['enSrt','jaSrt','frSrt','zhSrt','zhTwSrt'],
        captionArr: {},
				videoData: {},
				srtId: null
			}
		},
		watch: {
			step: {
				handler: function (e) {
					this.disabled = e == 2||this.$route.query.type=='detail'?true:false
					// if(e==2)this.getInfo()
				},
				immediate: true,
				deep: true
			},
			// "dialogVisible": {
      // 	handler: function (val) {
			// 		if(!val){
			// 			this.srtLang = 'en-US'
			// 			this.langList = []
			// 		}
			// 	},
			// 	immediate: true,
     	// 	deep: true 
			// }
		},
		computed: {
			setLang(){
				return (e)=>{
					return e=='en-US'?this.$t('short_data.subtitle.english'):e=='ja-JP'?this.$t('short_data.subtitle.japanese'):e=='zh-CN'?this.$t('short_data.subtitle.simplified'):e=='fr-FR'?this.$t('short_data.subtitle.french'):this.$t('short_data.subtitle.traditional')
				}
			},
			setShortName(){
				return (e)=>{
					return e&&(e[this.$i18n.locale]||e['en_US'])
				}
			},
			icon() {
				// return function(){
					const dUrl = decodeURIComponent(this.form.fileUrl);
					const str = dUrl.split('?')[0].split('.');
					console.log('fileType',str[str.length-1]);
					const type = str[str.length-1];
					if(type){
						if(['jpg','jpeg','png','gif','webp','tiff','bmp','heif','svg'].includes(type)){
							return 'sc-icon-img'
						}else if(['mp3','wma','ape'].includes(type)){
							return 'sc-icon-mp3'
						}else if(['mp4','mp5','avi','wmv'].includes(type)){
							return 'sc-icon-video'
						}else if(['pdf','txt','xlsx'].includes(type)){
							return 'sc-icon-pdf'
						}else{
							return 'sc-icon-none'
						}
					}
					return 'sc-icon-none'
				// }
			},
			oicon(){
				return function(e){
					return e
				}
			},
		},
		async mounted(){
			this.$store.commit("updateViewTagsTitle", this.$t('short_data.subtitle.title'))
			this.$nextTick(()=>{
				this.getInfo();
			});
			this.gptForm.words = this.$TOOL.data.get('word') || [];

		},
		methods: {
			contrastSrt() {
				this.gptForm.showContrast = !this.gptForm.showContrast;
			},
			restartAsk() {
				this.gptForm.showContrast = false;
				this.type = 3;
				this.gptForm.srtText = '';
				this.gptForm.originalSrt = '';
				this.gptForm.isTransEnd = false;
				this.submitData()
			},
			countinueAsk() {
				this.gptForm.showContrast = false;
				let lastSrt = this.srtList[this.srtList.length-1];
				let sTime = lastSrt.stime;
				let eTime = lastSrt.etime;
				let index = lastSrt.index;
				let error1 = this.gptForm.srt.split(`${sTime}-->${eTime}`);
				let error2 = this.gptForm.srt.split(`${sTime} -->${eTime}`);
				let error3 = this.gptForm.srt.split(`${sTime}--> ${eTime}`);
				let right = this.gptForm.srt.split(`${sTime} --> ${eTime}`);
				if(error1.length > 1) {
					this.gptForm.srt = `${index}\n${sTime} --> ${eTime}${error1[1]}`;
				}
				if(error2.length > 1) {
					this.gptForm.srt = `${index}\n${sTime} --> ${eTime}${error2[1]}`;
				}
				if(error3.length > 1) {
					this.gptForm.srt = `${index}\n${sTime} --> ${eTime}${error3[1]}`;
				}
				if(right.length > 1) {
					this.gptForm.srt = `${index}\n${sTime} --> ${eTime}${right[1]}`;
				}
				let srtSplitText = this.gptForm.srtText.split(`${index}\n${sTime} --> ${eTime}`);
				if(srtSplitText.length > 1) {
					try {
						let endText = this.gptForm.originalSrt.split(`${sTime} --> ${eTime}`)[1];
						if(endText.split('-->').length > 1) {
							this.gptForm.srtText = srtSplitText[0];
							this.submitData();
						} else {
							this.gptForm.isTransEnd = true;
							this.$message.success('已全部翻译完成');
						}
					} catch (error) {
						console.warn(error);
					}
				} else {
					// this.gptForm.isTransEnd = true;
					this.$message.success('翻译文本内容识别错误，请修改后重新翻译');
					this.gptForm.srtText += '\n\n';
				}
				// console.log('继续提问', this.gptForm.srt, this.gptForm.srtText);
			},
			changeLang(e) {
				console.log('changeLang', e);
				if (e == 'ja-JP') {
          this.gptForm.promptWord = 'The following content is in English SRT subtitle format text. Please translate it into Japanese language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
        } else if (e == 'en-US') {
          this.gptForm.promptWord = 'The following content is in Japanese SRT subtitle format text. Please translate it into English language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
        } else if (e == 'zh-CN') {
          this.gptForm.promptWord = 'The following content is in Japanese SRT subtitle format text. Please translate it into Simplified Chinese language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
        } else if (e == 'zh-TW') {
          this.gptForm.promptWord = 'The following content is in Japanese SRT subtitle format text. Please translate it into Traditional Chinese language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
        } else if (e == 'fr-FR') {
          this.gptForm.promptWord = 'The following content is in Japanese SRT subtitle format text. Please translate it into French language, maintaining the original format and line break structure, only translating the subtitle content itself, and returning the standard SRT format result as input to me.';
        }
			},
			submitData() {
				let data = {
					system: this.gptForm.promptWord,
					userChat: this.gptForm.srt,
				};
				if(!this.gptForm.originalSrt)this.gptForm.originalSrt = this.gptForm.srt;
				this.gptForm.isLoading = true;
				this.srtLang = this.gptForm.srtLang;
				if(this.gptForm.words.length > 10) {
					this.gptForm.words.unshift(this.gptForm.promptWord);
					this.gptForm.words.splice(10, 1);
				} else {
					this.gptForm.words.unshift(this.gptForm.promptWord);
				}
				this.$TOOL.data.set('word', this.gptForm.words);
				this.$API.ai.postAI.post(data).then(res => {
					// console.log('res', res);
					this.gptForm.isLoading = false;
					this.gptForm.transResultText = res.data||'';
					if(res.code == "OK" && res.data) {
						this.showGptDialog = false;
						this.showUploadBox = false;
						this.srtList = []
						this.handlePop(4,false)
						this.gptForm.srtText = this.gptForm.srtText + res.data;
						this.handleSrt(this.gptForm.srtText);
					} else {
						this.$message.error('返回内容不是SRT格式字幕，请检查提示词和翻译内容');
					}
				}).catch(err=>{
					console.log('err', err);
				})
			},
			initiateGPT() {
				this.showGptDialog = true;
			},
      // async inputFile(event) {
      //   const files = event.target.files;
			// 	const ffVideo = {
			// 		name: files[0].name,
			// 		file: files[0],
			// 		duration: 10
			// 	};
			// 	if(!ffmpeg.isLoaded())await ffmpeg.load()
			// 	let { name, file, duration } = ffVideo;
			// 	ffmpeg.FS("writeFile", name, await fetchFile(file));
			// 	// 计算每秒需要抽的帧数
			// 	let step = Math.ceil(20 / duration),
			// 		allNum = Math.floor(step * duration);
			// 	await ffmpeg.run(
			// 		"-i",
			// 		name,
			// 		"-r",
			// 		`${step}`,
			// 		"-ss",
			// 		"0",
			// 		"-vframes",
			// 		`${allNum}`,
			// 		"-f",
			// 		"image2",
			// 		"-s",
			// 		`500*300`,
			// 		"image-%02d.png"
			// 	);
			// 	for (let i = 0; i < allNum; i++) {
			// 		console.log('帧', i, allNum);
			// 	// 	let temp = i + 1;
			// 	// 	if (temp < 10) {
			// 	// 		temp = "0" + temp;
			// 	// 	}
			// 	// 	let buffer = ffmpeg.FS("readFile", "image-"+temp+".png")
			// 	// 	if(i % 5 == 0 && this.fileList[index].fpsList.length < 3){
			// 	// 		this.fileList[index].fpsList.push('data:image/png;base64,'+this.arrayBufferToBase64(buffer));
			// 	// 	}
			// 	}
			// },
			dragTimeChange(e){
				let video = this.$refs.video;
				try {
					video.currentTime = e;
					this.timelineData.nowTime = this.formatSecondsToTime(e);
					this.getVideoTime()
					console.log('拖动获取时间',e,video.currentTime)
				}catch(e){console.log(e)}
			},
			onTimeupdate() {
				// this.getVideoTime();
			},
      getVideoTime(){
				try {
					let video = this.$refs.video;
					let currentTime = video.currentTime;
					for(let i=this.srtList.length-1;i>0;i--){
						if( currentTime < this.srtList[i].etimeStamp){
							this.current = i;
							console.log("Current time: " + currentTime,this.srtList[i]); 
							break;
						}
					}
				} catch(e) {
					console.warn(e);
				}
      },
			// 上传文件解析为字符串
			inputSrtFileToString(event){
        let files = event.target.files;
				if(files.length > 1){
					this.$message.error(this.$t('components.upload.maxError'))
					return
				}
				if(!files[0].name.includes('srt') && !files[0].name.includes('ass')){
					this.$message.error(this.$t('short_data.subtitle.typeTips'))
					return
				}
				let reader = new FileReader();
				reader.readAsText(files[0])
        reader.onload = (res) => {
					this.gptForm.srt = res.target.result.replace(/\r/g,'');
					console.log('toString', res);
					event.target.value = '';
        }
			},
			// 上传文件
			inputSrtFile(event){
				this.srtId = null;
        let files = event.target.files;
				if(files.length > 1){
					this.$message.error(this.$t('components.upload.maxError'))
					return
				}
				if(!files[0].name.includes('srt') && !files[0].name.includes('ass')){
					this.$message.error(this.$t('short_data.subtitle.typeTips'))
					return
				}
				if(files[0].name.includes('ass')) {
					this.handlePop(4,false)
					let time = new Date().getTime();
					const blob = new File([files[0]], 	`${time}.ass`,{ type: "text/ass" })
					console.log(blob)
					this.uploadFile(blob)
					return;
				}
				this.showUploadBox = false;
				let reader = new FileReader();
				reader.readAsText(files[0])
        reader.onload = (res) => {
					this.handlePop(4,false)
					this.pushSubtitle(res.target.result,0,'ja',true)
					this.pushLocaleSubtitle(files[0]);
					this.$nextTick(()=>{
						if(this.$refs.Timeline)this.$refs.Timeline.setTime(0)
					})
        }
			},
			// 上传字幕插入到字幕列表
			pushLocaleSubtitle(file) {
				const localeSrtUrl = URL.createObjectURL(file);
				this.$nextTick(()=>{
					let srt = this.cationArr.find(n=>n.type == this.srtLang);
					srt.src = localeSrtUrl
					if(this.m3u8Url) {
						this.hls = new Hls();
						this.hls.loadSource(this.m3u8Url);
						this.hls.attachMedia(this.$refs.video);
					}
				})

			},
			click_timeline(d){
				console.log('点击了',d)
			},
			setZoom(e){
				this.scale = e;
			},
			// 时间轴显示格式
			formatTime(time){
				if (time.isAfter(dayjs().format('YYYY-MM-DD 23:59:59'))) {
					return '24:00:00'
				}
				return time.format('HH:mm:ss')
			},
			// 滑块改变触发
			scaleChange(zoom){
				this.$refs.Timeline.setZoom(zoom)
				// console.log(zoom,this.scale)
			},
			getHour(e){
				this.scale = e*100
			},
			palyPause() {
				this.getVideoTime();
			},
			// 点击时间轴
			clickCanvas(e){
				this.$nextTick(()=>{
					let video = this.$refs.video;
					if(typeof(e) == 'object') return;
					video.currentTime = this.$TOOL.turnMillSecond(this.$TOOL.dateFormat(e,'hh:mm:ss'),true)
					// this.timelineData.nowTime = this.$TOOL.dateFormat(e,'hh:mm:ss')
					console.log('点击获取时间',e,video.currentTime)
				})
			},
			delsubTitleMethods(index){
				this.srtList.splice(index,1)
				console.log('删除字幕',this.srtList)
			},
			addsubTitleMethods(item,index){
				let obj = {};
				Object.assign(obj,item);
				this.srtList.splice(index,0,obj)
				console.log('添加字幕',this.srtList)
			},
			viewZM(item,index){
				this.current = index;
				this.$refs.video.currentTime = item.stimeStamp;
				console.log(item,index)
			},
			handlePop(type,dialogVisible=false){
				this.type = type;
				this.dialogVisible = dialogVisible;
			},
      async pushSubtitle(str,ind,type,isResponse=false){
				this.srtList = []
        try {
					this.handleSrt(str);
          // this.cationArr[ind-1].src = this.captionArr[this.responseArr[ind]]
          // if(ind > 3){
          //   console.log('nword',this.srtList)
          //   return
          // }
          // let string = await this.dealCaption(this.captionArr[this.responseArr[ind]])
          console.log('str',isResponse,ind,type,this.srtList)
          // this.formatData(string,++ind,this.slangArr[ind-1])
        }catch(e){
          console.log('handleError',e)
        }
      },
			// 处理srt字幕
			handleSrt(str){
				let word = null;
				let isFG = str.includes('\r\n')?true:false;
				word = str.split('\n\n');
				if(isFG)word=str.split('\r\n\r\n')
				for(let i=0;i<word.length;i++){
					let nword = null;
					nword = word[i].split('\n');
					if(isFG)nword=word[i].split('\r\n')
					// if(nword.length==1&&i==0)this.videoForm.title = (nword[0])
					if(nword.length > 1 && nword[0] != "WEBVTT"){
						// let trimTimeSrt = nword[1].replace(/\s+/g, '');
						// if(!trimTimeSrt)break;
						// let stimeSplit = trimTimeSrt.split('-->')[0];
						// let etimeSplit = trimTimeSrt.split('-->')[1];
						// console.log(11111111, trimTimeSrt);
						let etime = this.handTime(nword[1].split(' --> ')[1].split(':'))
						let stime = this.handTime(nword[1].split(' --> ')[0].split(':'))
						let label = nword.splice(2,nword.length-2).join('\n');
						this.timelineData.markTime.push({
							beginTime: this.parseTimeToSeconds(nword[1].split(' --> ')[0]),
							endTime: this.parseTimeToSeconds(nword[1].split(' --> ')[1].trim()),
							color: "#c1a562",
							textColor: "#fff",
							text: label,
						});
						// if(ind == 1){
							this.srtList.push({
								index: nword[0].trim(),
								etime: nword[1].split(' --> ')[1].trim(),
								stime: nword[1].split(' --> ')[0],
								etimeStamp: etime,
								stimeStamp: stime,
								text: label
							})
						// } else {
							// this.srtList[i-1][this.lang[type]] = label
						// }
					}
				}
			},
			// 字幕时间转秒数
			parseTimeToSeconds(timeString) {
				// 定义正则表达式匹配时间格式
				const timeRegex = /^(\d{2}):(\d{2}):(\d{2})[.,](\d{3})$/;
				const match = timeString.match(timeRegex);

				if (!match) {
						throw new Error('时间格式不正确');
				}

				// 解析匹配的时间部分到变量
				const hours = parseInt(match[1], 10);
				const minutes = parseInt(match[2], 10);
				const seconds = parseInt(match[3], 10);
				const milliseconds = parseInt(match[4], 10);

				// 计算总秒数
				const totalSeconds = (hours * 3600) + (minutes * 60) + seconds + (milliseconds / 1000);

				return totalSeconds;
			},
			// 秒数转字幕时间
			formatSecondsToTime(totalSeconds) {
				// 确保输入的是非负数值
				totalSeconds = Math.max(0, parseFloat(totalSeconds));

				// 分离出整数部分和小数部分（毫秒）
				const integerPart = Math.floor(totalSeconds);
				const fractionalPart = (totalSeconds - integerPart).toFixed(3).slice(2); // 获取三位小数

				// 计算小时、分钟和秒数
				const hours = Math.floor(integerPart / 3600);
				const minutes = Math.floor((integerPart % 3600) / 60);
				const seconds = integerPart % 60;

				// 格式化输出，确保两位数显示，并添加毫秒
				const padWithZero = (num) => num.toString().padStart(2, '0');

				return `${padWithZero(hours)}:${padWithZero(minutes)}:${padWithZero(seconds)}.${fractionalPart}`;
			},
      handTime(etime){
        let h = parseInt(etime[0])*60*60;
        let m = parseInt(etime[1])*60;
        let s = parseInt(etime[2]?(etime[2].split('.').length==1?etime[2].split(','):etime[2].split('.'))[0]:'00');
        let hs = etime[2]?(etime[2].split('.').length==1?etime[2].split(','):etime[2].split('.'))[1]/1000:0;
				if(isNaN(h+m+s+hs)) {
					this.$message.error('字幕格式错误，请检查后');
				}
        return h+m+s+hs
      },
      // 获取本地file
      readFile(filePath) {
        // 创建一个新的xhr对象
        let xhr = null
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest()
        } else {
          // eslint-disable-next-line
          xhr = new ActiveXObject('Microsoft.XMLHTTP')
        }
        const okStatus = document.location.protocol === 'file' ? 0 : 200
        xhr.open('GET', filePath, false)
        xhr.overrideMimeType('application/pdf;charset=utf-8')
        xhr.send(null)
        return xhr.status === okStatus ? xhr.responseText : null
      },
			deleteSub(row){
				this.$confirm(this.$t('table_data.deltips1'), this.$t('table_data.tips'), {
					confirmButtonText: this.$t('table_data.editText'),
					cancelButtonText: this.$t('table_data.cancelText'),
					type: 'warning'
				}).then(async () => {
					var res = await this.$API.shorts.delSubtitle.delete(row.id);
					if(res.code == 'OK'){
						this.getInfo();
					}else{
						this.$alert(res.message, this.$t('table_data.tips'), {type: 'error'})
					}
				}).catch(() => {      
				});
			},
			async detail(row) {
				this.srtId = row.id;
				let video = this.$refs.video;
				this.timelineData.duration = 0;
				this.handlePop(4,false)
				let str = await this.readFile(row.srtUrl)
				this.srtLang = row.srtLang;
				this.pushSubtitle(str,0,'ja',false);
				this.$nextTick(()=>{
					this.timelineData.duration = video.duration;
					if(this.$refs.Timeline)this.$refs.Timeline.setTime(0)
				})
			},
			saveForm(data={}){
				Object.assign(this.form,data)
				console.log('内存form data:',this.form,data)
			},
			closeTag(){
				const tagList = this.$store.state.viewTags.viewTags;
				const tag = this.$route;
				const nowTagIndex = tagList.findIndex(item => item.fullPath == tag.fullPath)
				this.$store.commit("removeViewTags", tag)
				this.$store.commit("removeIframeList", tag)
				this.$store.commit("removeKeepLive", tag.name)

				const leftView = tagList[nowTagIndex - 1]
				if (leftView) {
					this.$router.push(leftView)
				} else {
					this.$router.push('/')
				}
			},
			// 保存字幕
			async saveSrt(){
				this.gptForm.isLoading = true;
				this.gptForm.srtText = '';
        let str = 'WEBVTT'+'\r\n\r\n';
        for(let i=0;i<this.srtList.length;i++){
          str += (i+1)+'\r\n'+(this.srtList[i].stime).replace(',','.')+' --> '+(this.srtList[i].etime).replace(',','.')+'\r\n'+this.srtList[i].text+'\r\n\r\n'
        }
				let time = new Date().getTime();
        const blob = new File([str], 	`${time}.srt`,{ type: "text/srt" })
        console.log(blob)
        this.uploadFile(blob)
			},
			// 上传字幕文件
      uploadFile(blob){
				let data = {}
        data.type = 10
				data.file = blob
        data.category = 10
				this.$API.upload.upload.post(data,{}).then(async res => {
					let srtData = {
						lang: this.srtLang,
						fileId: res.data.file_id,
						dramaKey: this.$route.query.isExplore?this.videoData.id:this.videoData.dramaKey,
						previewId: this.$route.query.previewId||null,
						id: this.srtId
					}
					let api = this.$API.subtitle.uploadSrtRequest;
					if(this.$route.query.isExplore)api = this.$API.subtitle.uploadExploreSrtRequest;
					await api.post(srtData)
					this.$message.success(this.$t('banner_data.uploadSuccessText'))
					this.type -= 1;
					this.gptForm.isLoading = false;
					this.getInfo();
        })
      },
			async canplay(){
				try {
					let video = this.$refs.video;
					this.timelineData.startMeddleTime = video.currentTime
					this.timelineData.timeRange.start = 0
					this.timelineData.timeRange.end = video.duration
					// this.timelineData.duration = video.duration
					this.timelineData.initTime = video.currentTime
					this.timelineData.nowTime = this.formatSecondsToTime(video.currentTime);
					this.current = this.srtList.findIndex(n=> video.currentTime >= n.stimeStamp && video.currentTime <= n.etimeStamp);
					
					console.log('canplay',video.currentTime,this.$TOOL.formateTime(video.currentTime),this.timelineData,video.clientWidth,video.clientHeight, 'video.duration：'+video.duration)
					// this.downloadImg()
				} catch(e) {
					console.warn(e);
				}
			},
			// 上架视频
			async publishVideo(){
				// let api = this.$API.shorts.publishVideo;
				// let shortId = this.$route.query.shortId;
				// await api.post({shortId: shortId});
				this.$message.success(this.$t('table_data.operasucc'))
				this.closeTag();
			},
			async getInfo(){
				let id = this.$route.query.id;
				let isExplore = this.$route.query.isExplore;
				this.subtitleList = [];
				let api = this.$API.subtitle.shortSrtDetail;
				if(isExplore){
					api = this.$API.subtitle.getExploreSrtDetail;
				}
				const res = await api.get(id);
				this.videoData = res.data;
				if(res.data.srtList.length){
					this.subtitleList = res.data.srtList
				} else {
					this.showUploadBox = true;
				}
				for(let i in res.data.srtList){
					let srt = this.cationArr.find(n=>n.type == res.data.srtList[i].srtLang);
					srt.src = res.data.srtList[i].srtUrl
				}
				if(res.data.m3u8Url && Hls.isSupported()){
					this.hls = new Hls(
						{
							xhrSetup: (xhr, url) => {
								// xhr.withCredentials = true;
								if(!url.endsWith('.m3u8')) {
									const token = this.$TOOL.cookie.get("TOKEN");// 替换为实际 token
									xhr.setRequestHeader("Authorization", `Bearer ${token}`); 
								}
								console.log('hls', xhr, url);

							},
							// autoStartLoad: true,
							// maxBufferLength: 30,
							// maxMaxBufferLength: 60,
							// enableWorker: true
						}
				);
					
					this.m3u8Url = this.$TOOL.handleM3u8Link(res.data.m3u8Url);
					// this.m3u8Url = res.data.m3u8Url;
					this.hls.loadSource(this.m3u8Url);
					this.hls.attachMedia(this.$refs.video);
				}
				
				
			},
			// 弹窗确认
			async submit(){
				if(this.type == 1){
					this.$refs.srtFile.dispatchEvent(new MouseEvent('click'));
				}
				if(this.type == 2){
					let data = {
						langCode: this.langList,
						dramaKey: this.$route.query.isExplore?this.videoData.id:this.videoData.dramaKey,
						videoFileKey: this.$route.query.isExplore?this.videoData.previewKey:this.videoData.videoFileKey
					};
					this.isWait = true;
					this.dialogVisible = false;
					let api = this.$API.subtitle.postAiSrt;
					if(this.$route.query.isExplore)api=this.$API.subtitle.postExploreAiSrt;
					try {
						const res = await api.post(data);
						if(res.code == "OK") {
							this.getInfo()
							this.gptForm.isLoading = false;
						}
					} catch (err) {
						console.log(err)
					}
					
				}
			}
		}
	}
</script>
<style scoped lang="scss">
.history {
	display: flex;
	flex-direction: column;
	margin-bottom: 10px;
	max-height: 334px;
	overflow-y: scroll;
	width: 740px;
	padding: 4px;
	span {
		color: #000;
		cursor: pointer;
		margin: 5px 0;
		padding: 4px;
	}
	span:hover {
		color: #fff;
		background: #000;
	}
}
.gptheadbox {
	display: flex;
  justify-content: space-between;
}
.cont-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.userbox {
	background: #fff;
	padding: 20px;
	margin: 16px;
	border: 1px solid #CCCCCC;
	border-radius: 4px;
	.sliderBox {
		.scrollbox {
			.timeline {
				width: 100%;
				height: 100px;
			}
			.timeOperabox {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20px;
				.leftside {
					width: 20%;
					display: flex;
					align-items: center;
					.leftside-time {
						width: 150px;
						margin-right: 20px;
					}
				}
				.rightside {
					width: 20%;
					display: flex;
					justify-content: flex-end;
					align-items: center;
					.slider {
						width: 50%;
					}
					.out_icon, .in_icon {
						margin: 0 12px;
						font-size: 20px;
						color: #999;
						cursor: pointer;
					}
				}
			}
		}
	}
  .scdialog-title {
    font-weight: 700;
    font-size: 20px;
  }
	.diaFooter {
		display: flex;
		justify-content: center;
	}
	#footer {
		display: flex;
		justify-content: center;
		margin-top: 10px;
	}
	h2 {
		margin-bottom: 20px;
	}
	.el-checkbox-group {
		display: flex;
    flex-direction: column;
    margin-top: 20px;
	}
	.popbtns {
		display: flex;
		justify-content: space-between;
		width: 100%;
		.localbtn {
			border: 1px dotted #888;
			padding: 32px 24px;
			color: #333;
			background: #F6F8F9;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			border-radius: 5px;
			cursor: pointer;
			line-height: 20px;
			text-align: center;
			width: 46%;
			.icon {
				width: 38px;
			}
		}
	}
	.operationbox {
		display: flex;
		justify-content: space-around;
	}
  .rightbox {
    width: 68%;
    height: 820px;
    overflow-y: scroll;
		margin-bottom: 50px;
		.formData {
			flex-direction: column;
			display: flex;
			align-items: flex-start;
			justify-content: flex-start;
			width: 100%;
			height: 88vh;
			/* overflow-y: scroll;*/
		}
		label {
			font-size: 14px;
			color: #eee;
		}
		.item {
			width: 100%;
			padding: 10px;
			font-size: 22px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border: 1px solid #ccc;
			position: relative;
		}
		.item:nth-child(2n) {
			
		}
		.isItem {
			background: #FFF8E6 !important;
		}
		.item-index {
			/* color: #eee;*/
			width: 5%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-direction: column;
			height: 100px;
			.xh {
				color: #888;
				font-size: 18px;
			}
			.del_icon,.add_icon {
				color: #000;
				cursor: pointer;
			}
			.del_icon {
				color: red;
			}
		}
		.item-time {
			width: 12%;
			display: flex;
			align-items: center;
			justify-content: flex-start;
			flex-direction: column;
			height: 100px;
		}
		.item-label {
			width: 78%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-direction: column;
			height: 100px;
			.textInput {
				max-height: 100px;
			}
		}
		.contrastbox {
			position: absolute;
			left: 0;
			width: 80px;
		}
		.timef {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-direction: column;
			height: 100px;
			.timeInput {
				height: 44px;
				font-size: 17px;
			}
		}
  }
	.gptCont {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 1rem;
		.allSrtbox {
			position: absolute;
			width: 97%;
			height: 77%;
			background: #fff;
			z-index: 999;
			display: flex;
			.form-group {
				width: 50%;
				height: 100%;
			}
		}
		.gptleftbox {
			width: 49%;
			.form-group {
				border: 1px solid #dbdbdb;
				label {
					padding: 4px;
					color: #000;
				}
			}
		}
		.gptrightbox {
			width: 49%;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			// max-height: 665px;
			.form-group {
				display: flex;
    		flex-direction: column;
				border: 1px solid #dbdbdb;
				margin-bottom: 10px;
				label {
					padding: 4px;
					color: #000;
				}
			}
			.el-radio-group {
				display: flex;
				flex-direction: column;
				align-items: flex-start;
			}
		}
	}
	.cont {
		display: flex;
		flex-direction: column;
		.subtitlebox {
			display: flex;
			justify-content: space-between;
			.videobox {
				width: 30%;
				.videoItem {
					width: 100%;
					height: 820px;
					border: 1px solid #CCCCCC;
					background: #000;
				}
				.addBtn {
					width: 100%;
					padding: 26px 0;
					font-size: 22px;
					margin-top: 30px;
				}
				.gptbtn {
					margin: 0;
					margin-top: 10px;
				}
			}
			.oprationbox {
				width: 68%;
				max-height: 500px;
				.btns {
					display: flex;
					justify-content: flex-start;
					.localbtn {
						margin-right: 20px;
						border: 1px dotted #888;
						padding: 20px 24px;
						color: #333;
						background: #F6F8F9;
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
						border-radius: 5px;
						cursor: pointer;
						line-height: 20px;
						text-align: center;
						.icon {
							width: 38px;
						}
					}
				}
				.title {
					font-size: 18px;
					font-weight: 400;
					line-height: 23.76px;
					text-align: left;
					margin-bottom: 20px;
				}
				.tips {
					font-size: 12px;
					font-weight: 700;
					line-height: 40px;
					text-align: left;
					color: #888;
				}
			}
		}
	}
}
</style>
